/* ====================================== Select  ====================================== */
import React from 'react'
// ===================================================================== 
const { $Lazy, $fn } = window
// ===================================================================== 
const Cascader = $Lazy.load(()=>import('@antd/form/cascader'))
// const $address = $Lazy.file(()=>import('#private/address'))
// ===================================================================== 
class Index extends React.Component {
	state = {
		data: []
	}
	
	componentDidMount(){
		this.init()
	}
	
	init = async callback => {
		let { data } = this.state
		if(!$fn.hasArray(data)){
			data = await $fn.dataSave('area/index')
			if(!$fn.hasArray(data)){
				data = await this.getData(100000)
			}
			
			if($fn.hasArray(data)){
				this.setState({ data })
			}
		}
		return data
	}
	
	getData = pid => {
		return window.$http.submit(this,'area/index', { param:{ pid }, loading:false }).then(data=>{
			const city = parseInt(String(pid).substring(2,4)) // 判断为城市编码
			
			data.forEach(v => {
				v.label = v.name
				v.value = v.id
				v.isLeaf = city !== 0
			})
			
			if(pid === 100000){
				$fn.dataSave('area/index', data)
			}
			
			return data
		})
	}
	// 动态加载数据
	loadData = async selectedOptions => {
		const targetOption = selectedOptions[selectedOptions.length - 1];
	
		targetOption.loading = true
		const _data =  await this.getData(targetOption['id'])
		
		targetOption.children = _data || []
		
		targetOption.loading = false
		
		this.setState(( { data } ) => ( { data:  [...data] } ))
	}
	// 回显加载数据
	load = async value => {
		const data = await this.init()
		
		if($fn.hasArray(value)){
			if(value[1]){
				// 获取 city
				const province_rows = data.filter( v=> v.value === value[0] )
				const city = await this.getData(value[0])
				
				if($fn.hasArray(province_rows)){
					province_rows[0].children =city
					
					if(value[2]){
						// 获取 area
						const city_rows = city.filter( v => v.value === value[1] )
						const area = await this.getData(value[1])
						
						if($fn.hasArray(city_rows)){
							city_rows[city_rows.length-1].children = area
						}
					}
				}
				
				this.setState({ data: [...data] })
			}
		}
	}
	
	onChanged = ({ name, value, option }) =>{
		const { onChanged, onChange  } = this.props
		
		const _option = { model: name ? { [name]: value } : value, value:value, 
			rows: $fn.hasArray(option) ? {
				province	: option[0]?.label,
				city		: option[1]?.label,
				area		: option[2]?.label,
				country_id	: '100000',
				province_id	: option[0]?.value,
				city_id		: option[1]?.value,
				area_id		: option[2]?.value,
			} : {}
		}
		
		onChanged && onChanged(_option)
		
		onChange && onChange(value)
	}
	
	
	
	render(){
		const { data } = this.state
		return (
			<Cascader {...this.props} data={data} hasOnChange onChanged={this.onChanged} loadData={this.loadData} changeOnSelect />
		)
	}
}
export default Index